<style rel="stylesheet/scss" lang="scss" scoped>
	.property-con {
		display: flex;
		height: 100%;
		width: 100%;
		flex-direction: column;
	}

	.property-box {
		display: flex;
		height: 100%;
		width: 100%;
		.f-cation {
			flex: 1;
			display: flex;
			height: auto;
			overflow: auto;
			padding: 0 5px 0;
			border: 1px solid #e5e5e5;
			flex-direction: column;
			margin-top: 10px;

			.f-cation_btn {
				width: 100%;
				height: 30px;
				color: #fff;
				display: flex;
				line-height: 30px;
				padding-left: 10px;
				cursor: pointer;
				font-size: 14px;
				background: #409EFF;
				span {
					flex: 1;
					text-align: center;
				}
			}
			.f-cation_info {
				width: 100%;
				flex: 1;
				font-size: 14px;
				flex-direction: column;
				overflow: auto;
				display: block;
				-webkit-padding-start: 0px;
				.info-item {
					width: 100%;
					height: 40px;
					display: flex;
					align-items: center;
					line-height: 40px;
					padding-left: 10px;
					border-bottom: 1px solid #e5e5e5;
					cursor: pointer;
					.info-item_div {
						flex: 1;
						display: flex;
						justify-content: flex-end;
						align-items: flex-end;
						>span {
							cursor: pointer;
						}
						.text-s {
							color: #409EFF;
							margin: 0 10px;
						}
					}
					i {
						margin-top: 10px;
						margin-right: 5px;
					}
				}
				.current {
					background: #f0f0f0;
				}
			}
		}
		.f-cation_box {
			flex: 3;
			overflow: auto;
			height: auto;
		}
		.ta {
			flex: 1;
			width: 100%;
			height: 500px;
			overflow: auto;
		}
		.text-s {
			color: #409EFF;
			margin: 0 10px;
			cursor: pointer;
		}
		.text-red {
			cursor: pointer;
		}
		.box-flex {
			display: flex;
			align-items: center;
		}
		.sp-w-50 {
			width: 100px;
			line-height: 40px;
		}
		.text-not {
			width: 100%;
			height: 40px;
			line-height: 40px;
			text-align: center;
			color: #666;
		}
		.radio-box {
			border: 1px solid #dcdfe6;
			border-radius: 100%;
			width: 14px;
			height: 14px;
			background-color: #fff;
			cursor: pointer;
			-webkit-box-sizing: border-box;
			box-sizing: border-box;
		}
		.tab-box {
			flex: 1;
			overflow: auto;
			display: flex;
			height: 200px;
		}
	}

	.inputBox {
		border: 1px solid #409EFF;
	}

	.btn-box {
		display: flex;
		justify-content: center;
	}
</style>
<template>
	<div class="property-con">
		<div class="property-box">
			<div class="f-cation">
				<!-- <el-input placeholder="请填写品牌名称"  suffix-icon="el-icon-edit" v-model="goodsBrand" class="m-t-10 inputBox" size="mini" autofocus="true">
				</el-input> -->
				<p class="f-cation_btn">
					<span>一级分类</span>
				</p>
				<ul class="f-cation_info" v-if="firstCatList && firstCatList.length>0">
					<li class="info-item" v-for="(item, index) in firstCatList" :class="{'current': currentIndex == index}" @click="selectItem(item, index)">
						<span>{{item.label}}</span>
						<div class="info-item_div">
						</div>
						<i class="el-icon-arrow-right"></i>
					</li>
				</ul>
			</div>
			<div class="f-cation" style="margin: 10px 5px 0;">
				<p class="f-cation_btn">
					<span>二级分类</span>
				</p>
				<ul class="f-cation_info" v-if="secCatList && secCatList.length>0">
					<li class="info-item" v-for="(item, index) in secCatList" :class="{'current': radioValue == item.label}" @click.prevent.stop="selectSenItem(item)">
						<el-radio v-model="radioValue" :label="item.label"></el-radio>
					</li>
				</ul>
			</div>
			<div class="f-cation f-cation_box">
				<p class="f-cation_btn">
					<font @click="addCat">新增+</font>
					<span>产品数据（仅注册会员可见需先开通会员功能）</span>
				</p>
				<template>
					<div class="tab-box">
						<el-table ref="multipleTable" :data="queryList" tooltip-effect="dark" width="1005" height="100%" @selection-change="handleSelectionChange">
							<el-table-column type="selection" align="center">
							</el-table-column>
							<el-table-column label="属性名称" prop="propertyName" align="center"></el-table-column>
							<el-table-column prop="propertyGroup" label="所属组" align="center">
							</el-table-column>
							<el-table-column prop="contentType" label="所属类型" align="center">
								<template slot-scope="scope">
									{{scope.row.propertyType == 1 ? '文本': scope.row.propertyType == 2 ? '文本链接':scope.row.propertyType == 3 ? '纯图片':
									'图片链接'}}
								</template>
							</el-table-column>
							<el-table-column prop="visibility" label="所有用户可见" align="center" >
								<template slot-scope="scope">
									<input type="radio" :id="'check'+scope.$index" checked="checked" value="1" class="radio-box" @change="changeItem(scope.row,scope.$index,1)"
									/>
								</template>
							</el-table-column>
							<el-table-column prop="contentType" label="仅注册用户可见" align="center" >
								<template slot-scope="scope">
									<input type="radio" value="2" :id="'checkbox'+scope.$index" class="radio-box" @change="changeItem(scope.row,scope.$index,2)"
									/>
								</template>
							</el-table-column>
							<el-table-column prop="sort" label="顺序" show-overflow-tooltip align="center">
							</el-table-column>
							<el-table-column label="操作" width="100" align="center">
								<template slot-scope="scope">
									<span class="text-s" @click="editFn(scope.row)">编辑</span>
									<span class="text-red" @click="deleteFn(scope.row)">删除</span>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</template>
			</div>
		</div>
		<el-dialog :title="title" :visible.sync="centerDialogVisible" width="45%" center>
			<el-row class="p-all-20 ">
				<el-col :span="20" class="box-flex m-b-10">
					<span class="sp-w-50 m-r-10">属性名称:</span>
					<el-input placeholder="属性名称" v-model="propertyName" maxLength="20" />
				</el-col>
				<el-col :span="20" class="box-flex m-b-10">
					<span class="sp-w-50 ">属性类型:</span>
					<el-radio label="1" v-model="type">纯文本</el-radio>
					<el-radio label="2" v-model="type">文本链接</el-radio>
					<el-radio label="3" v-model="type">纯图片</el-radio>
					<el-radio label="4" v-model="type">图片链接</el-radio>
				</el-col>
				<el-col :span="20" class="box-flex m-b-10">
					<span class="sp-w-50 m-r-10">所属组名:</span>
					<el-input placeholder="所属组名" v-model="groupName" maxLength="20" />
				</el-col>
				<el-col :span="20" class="box-flex m-b-10">
					<span class="sp-w-50 m-r-10">顺序号:</span>
					<el-input v-model="num" type="number" placeholder="顺序号" maxLength="5" oninput="if(value.length>5)value=value.slice(0,5)"
					/>
				</el-col>
			</el-row>
			<span slot="footer" class="dialog-footer">
				<el-button @click="centerDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="saveAdmin">确 定</el-button>
			</span>
		</el-dialog>
		<div class="btn-box m-t-10">
			<el-button type="primary" size="mini" @click="nextStep" :disabled="c_filter_next">下一步</el-button>
		</div>
	</div>
</template>
<script>
	import {
		mapMutations,
		mapGetters
	} from 'vuex'
	import {
		getToken
	} from '@/utils/auth'
	import {
		SUCCESS_REQUEST_STATUS
	} from '@/utils/config.js'
	export default {
		data() {
			return {
				radioValue: '', // 二级选中值
				firstCatList: [], // 一级分类数组
				secCatList: [], // 二级分类数组
				cateObject: null,
				currentIndex: 0,
				secCatIndex: 0,
				queryList: [],
				propertyName: '',
				type: '',
				id: '',
				catId: '',
				targetObj: null,
				groupName: '',
				num: '',
				title: '新增属性',
				centerDialogVisible: false,
				multipleSelection: []
			}
		},
		created() {
			this._getCategory({
				firCatId: this.getStepCache.firstCartId ? this.getStepCache.firstCartId : '',
				secCartId: this.getStepCache.secondCartId ? this.getStepCache.secondCartId　 : 　''
			})
		},
		methods: {
			// 删除
			deleteFn(item) {
				this.$confirm("确定删除此二级品类属性?", "删除二级品类属性", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(() => {
					
					this.$delete({
						url: `goods/category/property/${item.id}`,
						callback: res => {
							if(res.status === SUCCESS_REQUEST_STATUS) {
								this.$message({
									message: '删除成功',
									type: 'success'
								})
								if(this.getStepCache.queryAttrList) {
									this.getStepCache.queryAttrList.forEach((element, index) => {
										// 如果是新增的就不存在keyId 只有id
										if((item.id == element.id || item.id == element.keyId)) {
											this.getStepCache.queryAttrList.splice(index,1)
										}
									})
								}
								this.queryList = []
								this._getQueryAttr()
							}else {
								this.$message({
									message: res.msg,
									type: 'warning'
								});
							}
						}
					})
//					this.$ajax({
//						api: 'merchant/category/delAttr',
//						params: {
//							token: getToken(),
//							id: item.id,
//							merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') :
//								'',
//						}
//					}).then(res => {
//						if (res.status === SUCCESS_REQUEST_STATUS) {
//							this.$message({
//								message: '删除成功',
//								type: 'success'
//							});
//							if(this.getStepCache.queryAttrList) {
//								this.getStepCache.queryAttrList.forEach((element, index) => {
//									// 如果是新增的就不存在keyId 只有id
//									if((item.id == element.id || item.id == element.keyId)) {
//										this.getStepCache.queryAttrList.splice(index,1)
//									}
//								})
//							}
//							this.queryList = []
//							this._getQueryAttr()
//						} else {
//							this.$message({
//								message: res.data.message,
//								type: 'warning'
//							})
//						}
//					}).catch((err) => {
//						this.$message({
//							message: err.message,
//							type: 'warning'
//						});
//					})
				})
			},
			changeItem(item, index, val) {

				if (val == 1) {
					let preCheck = document.getElementById('checkbox' + index)
					preCheck.checked = false
					item.allView = true
					item.memberView = false
				} else {
					item.allView = false
					item.memberView = true
					let preCheck = document.getElementById('check' + index)
					preCheck.checked = false
				}
			},
			// 下一步
			nextStep() {
				// 对比选择跟缓存中的是否有不同的 添加到缓存中
				this.multipleSelection.forEach((item) => {
					item.attrId = item.id
					item.keyId = item.id
				})
				console.log(this.getStepCache)
				let attrObj = Object.assign({}, this.getStepCache,{queryAttrList: this.getStepCache.queryAttrList ? this.handleHeavyFn(this.multipleSelection, this.getStepCache.queryAttrList) : this.multipleSelection})
				console.log('设置后')
				console.log(this.getStepCache)
				this.setStepCache(attrObj)
				this.$emit('nextStep', this.catId)
//				return
//				this.$ajax({
//					api: 'merchant/goods/add1',
//					contentType: true,
//					params: {
//						attr: this.multipleSelection,
//						catId: this.catId,
//						token: getToken(),
//						merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') :
//							''
//					}
//				}).then(res => {
//					if (res.status === SUCCESS_REQUEST_STATUS) {
//						
//					} else {
//						this.$message({
//							type: 'error',
//							message: res.data.message
//						})
//					}
//				}).catch(err => {
//					this.$message({
//						type: 'error',
//						message: err.message
//					})
//				})
			},
			/**
			 * @desc 处理缓存中需要添加新数组 
			 * @params oldArr Array 当前选中的数组
			 * @params allArr Array 当前缓存的数组
			 */
			handleHeavyFn(oldArr, allArr) {
				for (let i = 0; i < oldArr.length; i++) {　　
					let flag = true　　
					for (let j = 0; j < allArr.length; j++) {　　　　
						if (oldArr[i].id == allArr[j].keyId) {　　　　　　
							flag = false　　　
						}
					}　
					if (flag) {　　　　
						allArr.push(oldArr[i]);　　
					}
				}
				return allArr
				
			},
			/**
			* @desc 编辑属性
			* @params item  当前选中的属性列表
			*/
			editFn(item) {
				console.log(item)
				this.title = '编辑属性'
				this.id = item.id
				alert(this.id)
				this.propertyName = item.propertyName
				this.groupName = item.propertyGroup
				this.num = item.sort +''
				this.type = item.propertyType +''
				console.log(typeof this.type)
				this.centerDialogVisible = true
				this.targetObj = item
				
			},
			handleSelectionChange(val) {
				this.multipleSelection = val
				console.log(this.getStepCache.queryAttrList)
				console.log(this.multipleSelection)
				if(this.getStepCache.queryAttrList !=null && this.getStepCache.queryAttrList.length &&  this.multipleSelection.length){
					this. multipleSelection.forEach((child ) => {
						this.getStepCache.queryAttrList.forEach((item) =>{
							if(child.id == item.keyId ){
								child.keyId = item.keyId
								child.content = item.content
								child.contentUrl = item.contentUrl
							}
						})
					})
				}
				console.log(this.multipleSelection)
				setTimeout(() => {
					this.getStepCache.queryAttrList = this.multipleSelection
				},200)
			},
			addCat() {
				this.title = '新增属性'
				this.targetObj = null
				this.centerDialogVisible = true
				this.id = this.propertyName = this.groupName = this.num = this.type = ''
			},
			selectSenItem(item) {
				this.catId = item.value
				let attrObj = Object.assign({}, this.getStepCache, {
					secondCartId: this.catId
				})
				this.setStepCache(attrObj),
				this.radioValue = item.label
				this.queryList = []
				this._getQueryAttr()
			},
			// 选择一级分类
			selectItem(item, index) {
				this.secCatList = []
				this.queryList = []
				this.currentIndex = index
				this.radioValue = ''
				let attrObj = Object.assign({}, this.getStepCache, {
					firstCartId: item.value
				})
				this.setStepCache(attrObj)
				this.cateObject.forEach((element) => {
					if (element.id == item.value) {
						element.children.forEach((cel) => {
							let objs = {
								value: cel.id,
								label: cel.categoryName
							}
							this.secCatList.push(objs)
						})
					}
				})
			},
			saveProperty() {
				this.$post({
					url: 'goods/category/property/',
					data: {
						id: null,
						categoryId: this.catId,
						merchantId: window.sessionStorage.getItem('merchantId'),
						propertyGroup: this.groupName,
						propertyName: this.propertyName,
						propertyType: parseInt(this.type), 
						sort: parseInt(this.num),
						visibility: 1  
					},
					callback: res => {
						console.log(res)
						if(res.status === 200) {
							this.$message({
								type: 'success',
								message: '操作成功'
							})
							if (this.targetObj) {
								this.targetObj.groupName = this.groupName
								this.targetObj.sort = this.num
								this.targetObj.contentType = this.type
								this.targetObj.infoName = this.propertyName
								this.queryList.forEach((item) => {
									if (item.id == this.targetObj.id) {
										item = this.targetObj
									}
								})
								if(this.getStepCache.queryAttrList) {
									this.getStepCache.queryAttrList.forEach((element) => {
										// 如果是新增的就不存在keyId 只有id
										if((this.targetObj.id == element.id || this.targetObj.id == element.keyId)) {
											element.allView = this.targetObj.allView
											element.contentType = this.targetObj.contentType
											element.groupName = this.targetObj.groupName
											element.infoName = this.targetObj.infoName
											element.memberView = this.targetObj.memberView
											element.showStatus = this.targetObj.showStatus
											element.sort = this.targetObj.sort
										}
									})
								}
								this.targetObj = null
								this.centerDialogVisible = false
								return
							}
							this.centerDialogVisible = false
							this._getQueryAttr()
						}
					}
				})
			},
			editProperty() {
				this.$put({
					url: 'goods/category/property/',
					data: {
						id: this.id,
						categoryId: this.catId,
						merchantId: window.sessionStorage.getItem('merchantId'),
						propertyGroup: this.groupName,
						propertyName: this.propertyName,
						propertyType: parseInt(this.type), 
						sort: parseInt(this.num),
						visibility: 1  
					},
					callback: res => {
						console.log(res)
						if(res.status === 200) {
							this.$message({
								type: 'success',
								message: '操作成功'
							})
							console.log(this.targetObj)
							if (this.targetObj) {
								this.targetObj.propertyGroup = this.groupName
								this.targetObj.sort = this.num
								this.targetObj.propertyType = this.type
								this.targetObj.propertyName = this.propertyName
								this.queryList.forEach((item) => {
									if (item.id == this.targetObj.id) {
										item = this.targetObj
									}
								})
								if(this.getStepCache.queryAttrList) {
									this.getStepCache.queryAttrList.forEach((element) => {
										// 如果是新增的就不存在keyId 只有id
										if((this.targetObj.id == element.id || this.targetObj.id == element.keyId)) {
											element.allView = this.targetObj.allView
											element.propertyType = this.targetObj.propertyType
											element.propertyGroup = this.targetObj.propertyGroup
											element.propertyName = this.targetObj.propertyName
											element.visibility = this.targetObj.visibility
											element.showStatus = this.targetObj.showStatus
											element.sort = this.targetObj.sort
										}
									})
								}
								this.targetObj = null
								this.centerDialogVisible = false
								this._getQueryAttr()
								return
							}
							
							this.centerDialogVisible = false
							this._getQueryAttr()
						}
					}
				})
				
			},
			saveAdmin() {
				let attr = !this.propertyName ? '请填写属性名称' : !this.type ? '请选择属性类型' : !this.groupName ? '请填写属性组' : !this.num ?
					'请填写顺序号' : ''
				if (attr) {
					this.$message({
						type: 'error',
						message: attr
					})
					return
				}
				this.id ? this.editProperty() : this.saveProperty()
				
				
			},
			_getQueryAttr() {
				this.$get({
					url: 'goods/category/property/',
					data: {
						merchantId: window.sessionStorage.getItem('merchantId'),
						categoryId: this.catId
					},
					callback: res => {
						if(res.status ===200) {
							this.queryList = res.data
							this.multipleSelection = []
							console.log(this.getStepCache.queryAttrList)
							console.log('选中的数据')
							setTimeout(() => {
								if (this.getStepCache.queryAttrList) {
									this.multipleSelection = this.getStepCache.queryAttrList
									this.getStepCache.queryAttrList.forEach((item, index) => {
										this.queryList.forEach((element) => {
											if (item.keyId == element.id) {
												this.$refs.multipleTable.toggleRowSelection(element, true);
											}
										})
									})
								}
							}, 200)
						}else {
							this.$message({
							message: res.msg,
							type: 'warning'
						})
						}
					}
				})
				return
				this.$ajax({
					api: 'merchant/category/queryAttr',
					params: {
						token: getToken(),
						catId: this.catId,
						merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') :
							''
					}
				}).then(res => 　{
					if (res.status === SUCCESS_REQUEST_STATUS) {
						this.queryList = res.data
						this.multipleSelection = []
						console.log(this.getStepCache.queryAttrList)
						console.log('选中的数据')
						setTimeout(() => {
							if (this.getStepCache.queryAttrList) {
								this.multipleSelection = this.getStepCache.queryAttrList
								this.getStepCache.queryAttrList.forEach((item, index) => {
									this.queryList.forEach((element) => {
										if (item.keyId == element.id) {
											this.$refs.multipleTable.toggleRowSelection(element, true);
										}
									})
								})
							}
						}, 200)
					} else {
						this.$message({
							message: res.data.message,
							type: 'warning'
						})
					}
				}).catch((err) => {
					this.$message({
						type: 'error',
						message: err.message
					})
				})
			},
			_getCategory(attr) {
				this.$get({
					url: 'goods/category/'+window.sessionStorage.getItem('merchantId'),
					callback: res => {
						console.log(res)
						if(res.status === 200) {
							if(res.data && res.data.length > 0) {
								res.data.forEach((item, index) => {
									let obj = {
										value: item.id,
										label: item.categoryName
									}
									this.firstCatList.push(obj)
								})
								if (!attr.firCatId) {
									let attrObj = Object.assign({}, this.getStepCache, {
										firstCartId: this.firstCatList[0].value
									})
									this.setStepCache(attrObj)
								}
								if (this.firstCatList.length) {
									this.firstCatList.forEach((item, index) => {
										if (attr && attr.firCatId == item.value) {
											this.currentIndex = index
										}
									})
									if (res.data[this.currentIndex]) {
										res.data[this.currentIndex].children.forEach((cel) => {
											let objs = {
												value: cel.id,
												label: cel.categoryName
											}
											this.secCatList.push(objs)
										})
									}
								}
								
								if (this.secCatList.length) {
									console.log(this.secCatList)
									console.log(attr.secCartId)
									setTimeout(() => {
										this.secCatList.forEach((items, secIndex) => {
											console.log(attr.secCartId == items.value,secIndex)
											if (attr && attr.secCartId == items.value) {
												console.log(this.secCatIndex)
												this.radioValue = items.label
												this.catId = items.value
												this.selectSenItem(items)
												this.secCatIndex = secIndex
											}
										})
									},200)
								}
								this.cateObject = res.data
								if (this.secCatList && this.secCatList.length > 0 && !attr.secCartId) {
									this.selectSenItem(this.secCatList[0])
								}
							}
						}
					}
				})
				return
				this.$ajax({
					api: 'merchant/category',
					params: {
						token: getToken(),
						merchantUserId: window.localStorage.getItem('merchantUserId') ? window.localStorage.getItem('merchantUserId') :
							''
					}
				}).then(res => {
					if (res.status === SUCCESS_REQUEST_STATUS) {
						if (res.data && res.data.length > 0) {
							res.data.forEach((item, index) => {
								let obj = {
									value: item.catId,
									label: item.catName
								}
								this.firstCatList.push(obj)
							})
							if (!attr.firCatId) {
								let attrObj = Object.assign({}, this.getStepCache, {
									firstCartId: this.firstCatList[0].value
								})
								this.setStepCache(attrObj)
							}
							if (this.firstCatList.length) {
								this.firstCatList.forEach((item, index) => {
									if (attr && attr.firCatId == item.value) {
										this.currentIndex = index
									}
								})
								if (res.data[this.currentIndex]) {
									res.data[this.currentIndex].children.forEach((cel) => {
										let objs = {
											value: cel.catId,
											label: cel.catName
										}
										this.secCatList.push(objs)
									})
								}
							}
							
							if (this.secCatList.length) {
								console.log(this.secCatList)
								console.log(attr.secCartId)
								setTimeout(() => {
									this.secCatList.forEach((items, secIndex) => {
										console.log(attr.secCartId == items.value,secIndex)
										if (attr && attr.secCartId == items.value) {
											console.log(this.secCatIndex)
											this.radioValue = items.label
											this.catId = items.value
											this.selectSenItem(items)
											this.secCatIndex = secIndex
										}
									})
								},200)
							}
							this.cateObject = res.data
							if (this.secCatList && this.secCatList.length > 0 && !attr.secCartId) {
								this.selectSenItem(this.secCatList[0])
							}
						}
					} else {
						this.$message({
							message: res.data.message,
							type: 'warning'
						})
					}
				}).catch((err) => {
					this.$message({
						type: 'error',
						message: err.message
					})
				})
			},
			...mapMutations({
				setStepCache: 'SET_STEP_CACHE',
			})
		},
		computed: {
			c_filter_next() {
				return this.catId && this.multipleSelection.length > 0 ? false : true
			},
			...mapGetters([
				'getStepCache'
			])
		}
	}
</script>
